using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using MauiBuilder.Services;
using System.Collections.ObjectModel;
using System.IO;

namespace MauiBuilder.ViewModels
{
    /// <summary>
    /// 日志条目模型
    /// </summary>
    public partial class LogEntry : ObservableObject
    {
        [ObservableProperty]
        private string _fileName = string.Empty;

        [ObservableProperty]
        private DateTime _createdTime;

        [ObservableProperty]
        private long _fileSize;
    }

    /// <summary>
    /// 日志页面视图模型
    /// </summary>
    public partial class LogPageViewModel : BaseViewModel
    {
        private readonly LogManager _logManager = LogManager.Instance;

        [ObservableProperty]
        private ObservableCollection<LogEntry> _logFiles = new();

        [ObservableProperty]
        private string _logContent = string.Empty;

        [ObservableProperty]
        private LogEntry? _selectedLogFile;

        [ObservableProperty]
        private bool _isBusy = false;

        public LogPageViewModel()
        {
            LoadLogFiles();
        }

        /// <summary>
        /// 加载所有日志文件
        /// </summary>
        [RelayCommand]
        private void LoadLogFiles()
        {
            try
            {
                IsBusy = true;
                LogFiles.Clear();

                string logDirectory = Path.Combine(FileSystem.AppDataDirectory, "Logs");
                if (Directory.Exists(logDirectory))
                {
                    var files = Directory.GetFiles(logDirectory, "app_log_*.log")
                        .OrderByDescending(f => f)
                        .ToArray();

                    foreach (var file in files)
                    {
                        var fileInfo = new FileInfo(file);
                        var logEntry = new LogEntry
                        {
                            FileName = Path.GetFileName(file),
                            CreatedTime = fileInfo.CreationTime,
                            FileSize = fileInfo.Length
                        };
                        string rrr = File.ReadAllText(file);
                        LogFiles.Add(logEntry);
                    }
                }
            }
            catch (Exception ex)
            {
                _logManager.LogError($"加载日志文件列表失败: {ex.Message}");
            }
            finally
            {
                IsBusy = false;
            }
        }

        /// <summary>
        /// 选择日志文件并加载其内容
        /// </summary>
        /// <param name="logFile">选中的日志文件</param>
        [RelayCommand]
        private void SelectLogFile(LogEntry logFile)
        {
            try
            {
                SelectedLogFile = logFile;
                LoadLogFileContent(logFile.FileName);
            }
            catch (Exception ex)
            {
                _logManager.LogError($"加载日志文件内容失败: {ex.Message}");
                LogContent = $"加载日志文件内容失败: {ex.Message}";
            }
        }

        /// <summary>
        /// 加载指定日志文件的内容
        /// </summary>
        /// <param name="fileName">日志文件名</param>
        private void LoadLogFileContent(string fileName)
        {
            try
            {
                string logDirectory = Path.Combine(FileSystem.AppDataDirectory, "Logs");
                string filePath = Path.Combine(logDirectory, fileName);

                if (File.Exists(filePath))
                {
                    LogContent = File.ReadAllText(filePath);
                }
                else
                {
                    LogContent = "日志文件不存在";
                }
            }
            catch (Exception ex)
            {
                _logManager.LogError($"读取日志文件内容失败: {ex.Message}");
                LogContent = $"读取日志文件内容失败: {ex.Message}";
            }
        }

        /// <summary>
        /// 删除选中的日志文件
        /// </summary>
        /// <param name="logFile">要删除的日志文件</param>
        [RelayCommand]
        private async Task DeleteLogFileAsync(LogEntry logFile)
        {
            try
            {
                var confirm = await AppShell.Current.DisplayAlert("确认删除", $"确定要删除日志文件 {logFile.FileName} 吗？", "确定", "取消");
                if (!confirm) return;

                string logDirectory = Path.Combine(FileSystem.AppDataDirectory, "Logs");
                string filePath = Path.Combine(logDirectory, logFile.FileName);

                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                    LogFiles.Remove(logFile);
                    
                    if (SelectedLogFile == logFile)
                    {
                        SelectedLogFile = null;
                        LogContent = string.Empty;
                    }
                    
                    await AppShell.Current.DisplayAlert("删除成功", $"日志文件 {logFile.FileName} 已删除", "确定");
                }
            }
            catch (Exception ex)
            {
                _logManager.LogError($"删除日志文件失败: {ex.Message}");
                await AppShell.Current.DisplayAlert("删除失败", $"删除日志文件失败: {ex.Message}", "确定");
            }
        }

        /// <summary>
        /// 刷新日志文件列表
        /// </summary>
        [RelayCommand]
        private void RefreshLogFiles()
        {
            LoadLogFiles();
        }

        /// <summary>
        /// 清除所有日志文件
        /// </summary>
        [RelayCommand]
        private async Task ClearAllLogsAsync()
        {
            try
            {
                var confirm = await AppShell.Current.DisplayAlert("确认清除", "确定要清除所有日志文件吗？", "确定", "取消");
                if (!confirm) return;

                string logDirectory = Path.Combine(FileSystem.AppDataDirectory, "Logs");
                if (Directory.Exists(logDirectory))
                {
                    var files = Directory.GetFiles(logDirectory, "app_log_*.log");
                    foreach (var file in files)
                    {
                        File.Delete(file);
                    }

                    LogFiles.Clear();
                    SelectedLogFile = null;
                    LogContent = string.Empty;
                    
                    await AppShell.Current.DisplayAlert("清除成功", "所有日志文件已清除", "确定");
                }
            }
            catch (Exception ex)
            {
                _logManager.LogError($"清除所有日志文件失败: {ex.Message}");
                await AppShell.Current.DisplayAlert("清除失败", $"清除所有日志文件失败: {ex.Message}", "确定");
            }
        }
    }
}